package com.wxp.demo08.fragment.adapter;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;

import com.wxp.demo08.fragment.fragment.DynamicFragment;
import com.wxp.demo08.shopping.entity.GoodsInfoEntity;
import com.wxp.demo08.util.CollectionUtils;

import java.util.List;

/**
 * 移动翻页 适配器
 * viewpage1: 使用 androidx.fragment.app.FragmentPagerAdapter
 * viewpage2: 使用 ndroidx.viewpager2.adapter.FragmentStateAdapter
 */
public class MobilePagerAdapter extends FragmentPagerAdapter {

    private final List<GoodsInfoEntity> mGoodsList;

    public MobilePagerAdapter(@NonNull FragmentManager fm, List<GoodsInfoEntity> goodsList) {
        // 会将当前fragment设置为Resume的状态，把上个fragment设置成Start的状态。
        // 从而可以通过fragment的onResume()来懒加载数据。
        super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
        this.mGoodsList = goodsList;
    }

    @NonNull
    @Override
    public Fragment getItem(int position) {
        GoodsInfoEntity info = mGoodsList.get(position);
        return DynamicFragment.newInstance(position, info.pic, info.description);
    }

    @Override
    public int getCount() {
        return CollectionUtils.isEmpty(mGoodsList) ? 0 : mGoodsList.size();
    }

    @Nullable
    @Override
    public CharSequence getPageTitle(int position) {
        return mGoodsList.get(position).name;
    }
}
